package com.szxy.poitl.controller;

import com.deepoove.poi.XWPFTemplate;
import com.szxy.poitl.domain.Author;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

/**
 * @Author: zwz
 * @Date:2020/7/25 14:51
 * @Description:com.szxy.poitl.controller
 * @Version:1.0
 **/
@Controller
public class WordController {

    public static final String FILE_NAME = "template.docx";

    @GetMapping("/test")
    public ResponseEntity test() {
        return ResponseEntity.ok().body("ok!");
    }

    @GetMapping("/toWord")
    public void toWord(HttpServletResponse response) throws IOException {
        // 获取绝对路径
        String path = WordController.class.getClassLoader().getResource(FILE_NAME).getPath();
        System.out.println(path);
        Author author = new Author();
        author.setAge(20);
        author.setName("小方");
        author.setSex("男");
        XWPFTemplate template = XWPFTemplate.compile(path)
                .render(new HashMap<String, Object>() {{
                    put("title", "Poi-tl 模板引擎");
                    put("content", "poi-tl（poi template language）是基于Apache POI的Word模板引擎，纯Java组件，跨平台，" +
                            "代码短小精悍，通过插件机制使其具有高度扩展性。");
                    put("author", author);
                }});
        // 以流的形式返回 word 文件内容
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=\"" + "downLoad.docx" + "\"");
        // 获取输出流
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        template.close();
        out.flush();
        out.close();
    }
}
